import { Button, Pagination, Popconfirm, Table, TableProps } from 'antd';
import { useEffect } from 'react';

import { post,usePost } from '@/api';

interface ApiModelAddProps extends HTMLElementProps {
  handleEdit: (row: DataType) => void;
}

export interface ApiTableRef {
  tableRequest: () => void;
}

interface DataType {
  id: string;
  apiName: string;
  httpUrl: number;
  apiDesc: string;
}

export const ApiTable = memo(
  forwardRef<ApiTableRef, ApiModelAddProps>((props, ref) => {
    const [current, setCurrent] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [total, setTotal] = useState(0);
    const [dataSource, setDataSource] = useState([]);

    const { loading, runAsync: queryApi } = usePost('/api/page', {}, { manual: true });
    const { runAsync: deleteApi } = usePost('/api/delete', {}, { manual: true });

    const columns: TableProps<DataType>['columns'] = [
      {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
        align: 'center',
        width: 80,
        render: (_, record, index) => {
          return <span>{index + 1}</span>;
        }
      },
      {
        title: 'API名称',
        dataIndex: 'apiName',
        key: 'apiName'
      },
      {
        title: '访问路径',
        dataIndex: 'httpUrl',
        key: 'httpUrl'
      },
      {
        title: 'API描述',
        dataIndex: 'apiDesc',
        key: 'apiDesc'
      },
      {
        title: '操作',
        key: 'action',
        fixed: 'right',
        width: 160,
        render: (_, record) => (
          <>
            <Button type="link" className="pl-0" onClick={() => props.handleEdit(record)}>
              修改
            </Button>
            <Popconfirm title="确定删除吗？" onConfirm={() => confirm(record)}>
              <Button type="text">删除</Button>
            </Popconfirm>
          </>
        )
      }
    ];

    const refresh = () => {
      queryApi({
        pageNo: current,
        pageSize
      } as never).then((data) => {
        if(data) {
          setTotal(data.total!);
          setDataSource(data.list!);
        }
      });
    };

    const handleSizeChange = (val: number) => {
      setPageSize(val);
      setCurrent(1);
    };
    const handleCurrentChange = (val: number) => {
      setCurrent(val);
    };

    const confirm = (record: DataType) => {
      console.log('🚀 ~ confirm ~ confirm: 删除', record);
      if (!record || !record.id) return;
      deleteApi({
        id: Number(record.id)
      } as never).then((data) => {
        refresh();
      });
    };

    useEffect(() => {
      refresh();
    }, [current, pageSize]);

    useImperativeHandle(ref, () => ({
      tableRequest: () => {
        refresh();
      },
    }));

    return (
      <div className="api-table h-full">
        <Table
          rowKey="id"
          dataSource={dataSource}
          columns={columns}
          pagination={false}
          loading={loading}
          scroll={{ x: 1200, y: 725 }}
        />
        <Pagination
          className='mt-20'
          defaultPageSize={20}
          defaultCurrent={1}
          total={total}
          align="end"
          showQuickJumper
          pageSizeOptions={[10, 20, 50, 100]}
          onChange={handleCurrentChange}
          onShowSizeChange={handleSizeChange}
        />
      </div>
    );
  })
);
